<script setup>
import { ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import { REQU, useResp, toFormData } from '@/net/requ.js';

const props = defineProps(['visible', 'id', 'menuInfo', 'funcInfo']);
const emit = defineEmits(['update:visible', 'ok']);

const visible = ref(props.visible);
watch(visible, value => emit('update:visible', value));

const sending = ref(false);

const rules = {
  functionName: [ { required: true, message: '请输入功能名称' } ],
  functionCode: [ { required: true, message: '请输入功能 code' } ],
};

// menuCode: '',
// interfaceCode: '',

const formElem = ref();

const FormState = () => ({
  functionName: '',
  functionCode: '',
  needShow: true,
  sort: 0,
});

const formState = ref(Object.assign(FormState(), props.funcInfo));

function save() {
  return REQU('/api/function/save', {
    method: 'POST',
    body: toFormData(Object.assign(
      {},
      formState.value,
      R.pick(['menuCode', 'interfaceCode'], props.menuInfo))
    ),
  })
  .then(useResp({
    succ: result => {
      message.success('保存成功');
      return result;
    },
    fail: result => {
      message.error(result.message);
      return result;
    },
  }))
}

function onOk() {
  formElem.value
  .validate()
  .then(save)
  .then(result => {
    if (200 == result.code) {
      emit('ok');
      visible.value = false;
    }
  })
  .catch(() => {});
}
</script>

<template>
  <a-modal
    :visible="visible"
    :title="`${ formState.id ? '编辑' : '新建' }功能`"
    @cancel="() => visible = false"
    @ok="onOk">
    <a-form
      ref="formElem"
      label-align="right"
      :label-col="{ span: 6 }"
      :model="formState"
      :rules="rules">
      <a-form-item required name="functionName" label="功能名称">
        <a-input
          v-model:value="formState.functionName"
          :disabled="sending"
          allow-clear
          placeholder="请输入功能名称">
        </a-input>
      </a-form-item>

      <a-form-item required name="functionCode" label="功能 code">
        <a-input
          v-model:value="formState.functionCode"
          :disabled="sending"
          allow-clear
          placeholder="请输入功能 code">
        </a-input>
      </a-form-item>

      <a-form-item required name="needShow" label="是否需要显示" :disabled="sending">
        <a-radio-group v-model:value="formState.needShow">
          <a-radio :value="true">需要</a-radio>
          <a-radio :value="false">不需要</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item name="sort" label="顺序">
        <a-input-number
          v-model:value="formState.sort"
          :min="0"
          :step="1"
          :disabled="sending">
        </a-input-number>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
